package com.zg.recycler.pad.ali;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.zg.recycler.pad.util.Constant;

import net.sf.json.JSONObject;

import org.apache.commons.codec.binary.Base64;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class TestFeisou {
//    private static String testUrl = "http://img1.imgtn.bdimg.com/it/u=947982974,538813931&fm=26&gp=0.jpg";
//    private static String testUrl1 = "http://pic47.nipic.com/20140904/18981839_095218870000_2.jpg";

    private static String doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys) {
        InputStream is = null;
        try {
            String strURL = host + path;
            URL url = new URL(strURL);// 创建连接  
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(method); // 设置请求方式  
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式              
            for (Entry<String, String> cc : headers.entrySet()) {
                connection.setRequestProperty(cc.getKey(), cc.getValue());
            }

            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            StringBuilder params = new StringBuilder();


            JSONObject array = net.sf.json.JSONObject.fromObject(bodys);
//            JSON object = JSONSerializer.toJSON(bodys);
//            System.out.println(array.toString() instanceof String);
//            System.out.println(array);
            out.write(array.toString());
            out.flush();
            out.close();

            is = connection.getInputStream(); // bug

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String temp = null;
            StringBuilder content = new StringBuilder();
            while ((temp = reader.readLine()) != null) {
                content.append(temp);
            }
            return content.toString();

        } catch (Exception e) {
            e.printStackTrace();
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e2) {
                    e.printStackTrace();
                }

            }
        }
        return "error"; // 自定义错误信息  
    }

    public static void main(String[] args) throws Exception {
        // System.out.println(ocrStoreInner("D:\\2.jpg"));
    }

    public static void  ocrStoreInner(Handler handler, String imageStr) throws Exception {
        String host = "http://object.market.alicloudapi.com";
        String path = "/v2/object/recognize";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:
        headers.put("Authorization", "APPCODE " + Constant.Feisouappcode);//替换您的appcode   别忘加空格！
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("img_base64", createImageStr(imageStr));
//        bodys.put("img_url", testUrl1);
        try {
            String response = doPost(host, path, method, headers, querys, bodys);
            Message msg = new Message();
            msg.what = 2;
            Bundle bundle = new Bundle();
            bundle.putString("data", response);
            msg.setData(bundle);
            handler.sendMessage(msg);
//            return response.toString();
        } catch (Exception e) {
            throw new Exception(String.format("ocr storeInnerImg:%s, errormsg:%s", new Object[]{imageStr, e.getMessage()}));
        }
    }

    /**
     * 将image转换为base64 String
     *
     * @param imageFilePath
     * @throws Exception
     * @returnlll
     */
    private static String createImageStr(String imageFilePath) throws Exception {
        if (imageFilePath == null || imageFilePath.trim().length() == 0) {
            throw new Exception(String.format("createImageStr but imageFilePath is %s.", new Object[]{imageFilePath}));
        }
        FileInputStream fis = new FileInputStream(imageFilePath);
        return createImageStr(fis);
    }

    /**
     * 将image转换为base64 String
     *
     * @param
     * @return
     * @throws Exception
     */
    private static String createImageStr(InputStream inputStream) throws Exception {
        if (inputStream == null || inputStream.available() == 0) {
            throw new Exception("createImageStr but inputstream is null.");
        }
        byte[] data = new byte[inputStream.available()];
        inputStream.read(data);
        inputStream.close();
        data = Base64.encodeBase64(data);
        String sr = null;
        if (data != null) {
            sr = new String(data);
        }
        return sr;
    }

}
